<?php

namespace LhpAmis\Traits;
use LhpAmis\Renderers\Amis;

trait IconifyPickerTrait
{
    /**
     * iconify 图标选择器
     *
     * @param string $api
     * @param string $name
     * @param string $label
     *
     * @return \LhpAmis\Renderers\PickerControl
     */
    protected function iconifyPicker(string $api, string $name = '', string $label = '')
    {
        $schema = Amis::make()->CRUDCards()
            ->perPage(40)
            ->loadDataOnce()
            ->set('columnsCount', 8)
            ->footerToolbar(['statistics', 'pagination'])
            ->api($api)
            ->filter(
                Amis::make()->Form()->wrapWithPanel(false)->body([
                    Amis::make()->GroupControl()->className('pt-3 pb-3')->body([
                        Amis::make()->TextControl('query')
                            ->size('md')
                            ->value('${' . $name . ' || "home"}')
                            ->clearable()
                            ->required(),
                        Amis::make()->Button()
                            ->label(lang('admin.search'))
                            ->level('primary')
                            ->actionType('submit')
                            ->icon('fa fa-search'),
                        Amis::make()->UrlAction()
                            ->className('ml-2')
                            ->icon('fa fa-external-link-alt')
                            ->label('Icones')
                            ->blank()
                            ->url('https://icones.js.org/collection/all'),
                    ]),
                ])
            )
            ->card(
                Amis::make()->Card()->body([
                    Amis::make()->SvgIcon()->icon('${icon}')->className('text-2xl'),
                ])
            );

        return Amis::make()->PickerControl($name, $label)
            ->pickerSchema($schema)
            ->source($api)
            ->size('lg')
            ->labelField('icon')
            ->valueField('icon');
    }

    protected function getIconifyList($query = 'home')
    {
        $icons = file_get_contents(dirname(__DIR__) . '/iconify.json');
        $icons = json_decode($icons, true);

        $items = [];
        foreach ($icons as $item) {
            if (str_contains($item, $query)) {
                $items[] = ['icon' => $item];
            }
            if (count($items) > 999) {
                break;
            }
        }

        $total = count($items);

        return compact('items', 'total');
    }
}
